import type { RouteObjectType } from "@/typings/router";
import type { MenuStoreType } from "@/typings/stores";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { devtools } from "zustand/middleware";
import { getSidebarMenuList, getFlatMenuList } from "@/routers/helper/GenerateRouter";

const initialState: MenuStoreType.stateType = {
  flatMenuList: [], // 扁平化后的菜单数据
  authMenuList: [], // 后端权限菜单数据
  sidebarMenuList: [], // 侧边栏菜单数据
  isCollapse: false // 侧边栏折叠开关
};

const actions = (set: MenuStoreType.settersStoreType) => {
  const setAuthMenuList = (menuList: RouteObjectType[]) => {
    set((state: MenuStoreType.stateType) => {
      state.authMenuList = menuList;
      state.flatMenuList = getFlatMenuList(menuList);
      state.sidebarMenuList = getSidebarMenuList(menuList);
    });
  };

  const setCollapsed = (isCollapse: boolean) => {
    set((state: MenuStoreType.stateType) => {
      state.isCollapse = isCollapse;
    });
  };

  const clearAuthMenu = () => {
    set(useMenuStore.getInitialState());
  };

  return { setAuthMenuList, setCollapsed, clearAuthMenu };
};

const devtoolsConfig = { name: "REACT_APP_MENUS_STORAGE", enabled: import.meta.env.VITE_APP_REDUX_DEVTOOLS === "true" };
export const useMenuStore = create<MenuStoreType.storeType>()(
  devtools(
    immer((set) => ({
      ...initialState,
      ...actions(set)
    })),
    devtoolsConfig
  )
);
